package secondkill.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import secondkill.pojo.TUser;
import secondkill.service.ITGoodsService;
import secondkill.service.ITUserService;
import secondkill.vo.GoodDetailVo;
import secondkill.vo.GoodsVo;
import secondkill.vo.RespBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 商品页面控制类
 * @Auther  丁子川
 * @create 2022/1/19 12:42
 */

@Slf4j
@Controller
@RequestMapping("/goods")
public class TGoodsController {

    @Autowired
    private ITGoodsService goodsService;

    @Autowired
    private ITUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //themeleaf渲染引擎
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

  //第一版
/*    @RequestMapping(value = "/toList")
    public String toList(Model model, HttpServletResponse response, HttpServletRequest request, @CookieValue("userTicket") String ticket) {
        if(StringUtils.isEmpty(ticket)){
            return "login";
        }
        //TUser user = (TUser) session.getAttribute(ticket);
        TUser user = userService.getUserByCookie(ticket, request, response);
        if (null == user){
            return "login";
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVoList());
        return "goodsList";
    }*/

  //第二版 解耦 在用户在调用Controller就校验用户是否登录过 通过自定义用户参数UserArgumentResolver
/*    @RequestMapping(value = "/toList")
    public String toList(Model model,TUser user) {
        model.addAttribute("user", user);
        model.addAttribute("goodsList",goodsService.findGoodsVoList());
        return "goodsList";
    }*/

    //第三版 页面缓存
    /**
     * 返回商品列表
     * @param model 
     * @param user 
     * @param response 
     * @param request
     * @return java.lang.String 
     * @create 2022/1/23 0:42
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, TUser user, HttpServletResponse response, HttpServletRequest request) {

        //Redis中获取页面, 如果不为空, 直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //html页面是以String类型存储 且名称为"goodsList"
        String html = (String) valueOperations.get("goodsList");
        if (!(null == html || "".equals(html))) {
            return html;
        }
        //将key与value添加进model
        model.addAttribute("user", user);
        model.addAttribute("goodsList",goodsService.findGoodsVoList());

        //如果为null手动渲染thymeleaf模板, 存如Redis并返回, 而不是SpringBoot来渲染
        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!(null == html || "".equals(html))) {
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    //第一版 跳转商品详情页
/*    @RequestMapping("/toDetail/{goodsId}")
    public String toDetail(Model model, TUser user, @PathVariable Long goodsId) {

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodsId);
        model.addAttribute("goods", goodsVo);
        //获取开始时间
        Date startDate = goodsVo.getStartDate();
        //获取结束时间
        Date endDate = goodsVo.getEndDate();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        if (new Date().before(startDate)) {
            //秒杀还没开始
            remainSeconds = ((int) (startDate.getTime() - new Date().getTime()) / 1000);
        } else if (new Date().after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        return "goodsDetail";
    }*/

    //第二版 URL静态缓存
/*    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, TUser user, @PathVariable Long goodsId, HttpServletResponse response, HttpServletRequest request) {
        //Redis中获取页面, 如果不为空, 直接返回页面, 且使用分级目录方式进行缓存
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail" + goodsId);
        if (!(null == html || "".equals(html))) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodsId);
        model.addAttribute("goods", goodsVo);
        //获取开始时间
        Date startDate = goodsVo.getStartDate();
        //获取结束时间
        Date endDate = goodsVo.getEndDate();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        if (new Date().before(startDate)) {
            //秒杀还没开始
            remainSeconds = ((int) (startDate.getTime() - new Date().getTime()) / 1000);
        } else if (new Date().after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);

        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);

        if (!(null == html | "".equals(html))) {
            valueOperations.set("goodsDetail" + goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }*/

    //第三版 使用页面静态化 传输数据不再是model 而是通过ajax来进行传输数据
    //先获取页面后再通过ajax获取数据 而不像前面先进行页面渲染再返回页面
    /**
     * 跳转商品详情页面
     * @param model 
     * @param user 
     * @param goodId
     * @return secondkill.vo.RespBean 
     * @create 2022/1/23 15:12
     */
    @RequestMapping("/detail/{goodId}")
    @ResponseBody
    public RespBean toDetail(Model model, TUser user, @PathVariable Long goodId) {
        model.addAttribute("tUser", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodId);
        model.addAttribute("goods", goodsVo);

        //获取开始时间
        Date startDate = goodsVo.getStartDate();
        //获取结束时间
        Date endDate = goodsVo.getEndDate();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        if (new Date().before(startDate)) {
            //秒杀还没开始
            remainSeconds = ((int) (startDate.getTime() - new Date().getTime()) / 1000);
        } else if (new Date().after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);

        GoodDetailVo goodDetailVo = new GoodDetailVo();
        goodDetailVo.setUser(user);
        goodDetailVo.setGoodsVo(goodsVo);
        goodDetailVo.setSecKillStatus(secKillStatus);
        goodDetailVo.setRemainSeconds(remainSeconds);
        log.info("goodDetailVo:{}",goodDetailVo);
        return RespBean.success(goodDetailVo);
    }

/*    @RequestMapping("/toAdd")
    public String toAdd() {
        return "addGood";
    }


    @ResponseBody
    @PostMapping("/addGood")
    public RespBean addGood(AddGoodVo addGoodVo) {

        //文件上传
        MultipartFile imgName = addGoodVo.getImgLoad();
        if (imgName.getSize() > 10485760) {
            return RespBean.error(RespBeanEnum.FILE_SIZE_OVER);
        }
        try {
            //处理文件上传
            String localPath = "C:\\Users\\lyx\\Desktop\\secKillPro\\seckill_pro\\seckillpro\\src\\main\\resources\\static\\imgs";
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/imgs";
            System.out.println(realPath);
            File localDir = new File(localPath);
            File realDir = new File(realPath);
            if (!localDir.exists()) {
                log.info(localPath + ":不存在");
            }
            if (!realDir.exists()) {
                log.info(realDir + ":不存在");
            }

            String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString();
            String extension = FilenameUtils.getExtension(imgName.getOriginalFilename());

            String newName = newFileNamePrefix + "." + extension;
            addGoodVo.setNewName(newName);
            File desFile = new File(realPath + "/" + newName);

            //上传到服务器
            FileUtils.copyInputStreamToFile(imgName.getInputStream(), desFile);
            //上传到本地
            imgName.transferTo(new File(localDir, newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return goodsService.addGood(addGoodVo);
    }*/

    /**
     * 删除商品
     * @param goodId
     * @param userId
     * @return RespBean
     * @create 2022/1/20 12:30
     */
/*    @RequestMapping("/delete/{goodId}")
    @ResponseBody
    public RespBean deleteGood(@PathVariable Long goodId, String userId) {

        System.out.println(userId);
        if (!userId.equals("17621806946")) {
            return RespBean.error(RespBeanEnum.IS_NOT_ADMIN);
        }
        RespBean respBean = goodsService.removeGood(goodId);
        Object o = redisTemplate.opsForValue().get("goodsList");
        if (!ObjectUtil.isEmpty(o)){

            redisTemplate.delete("goodsList");
        }
        return respBean;
    }*/

}